package com.chao.tlias.aop;

import com.chao.tlias.Pojo.OperateLog;
import com.chao.tlias.mapper.OperateLogMapper;
import com.chao.tlias.util.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 记录操作日志，存入数据库之中
 */
@Slf4j
@Aspect
@Component
public class OperationLogAspect {


    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.chao.tlias.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();//开始时间

        Object result = joinPoint.proceed();//执行原始方法

        //计算耗时
        long endTime = System.currentTimeMillis();//结束时间
        long costTime = endTime - startTime;

        //构造日志实体
        OperateLog olog = new OperateLog();
        olog.setOperateUser(getCurrenUserID());//操作用户ID
        olog.setOperateTime(LocalDateTime.now());//操作时间
        olog.setClassName(joinPoint.getTarget().getClass().getName());//操作类名
        olog.setMethodName(joinPoint.getSignature().getName());//操作方法名
        olog.setMethodParams(Arrays.toString(joinPoint.getArgs()));//操作方法参数
        olog.setReturnValue(result != null ? result.toString() : "");// 操作返回值
        olog.setCostTime(costTime);//操作耗时

        //保存日志
        log.info("操作日志：{}", olog);
        operateLogMapper.insert(olog);

        return result;

    }

    private Integer getCurrenUserID() {
        return CurrentHolder.getCurrent();
    }

}
